<?php
namespace app\admin\controller;


use app\admin\model\Bank;
use app\admin\model\BenefitLevel;
use app\admin\model\ModeOneLevel;
use app\admin\model\ModeThreeLevel;
use app\admin\model\Level;
use app\merchant\model\MerchantInfo;
use app\merchant\model\MerchantOrder;
use app\merchant\model\Order;
use think\facade\Session;
use think\facade\View;
use think\Request;

class User extends Base
{
    protected $ModelPath = 'User';
    protected $model = null;

    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->con = "User";
        $this->title = "用户";

        $module = strtolower($this->ModelPath);
        $this->model = new \app\admin\model\User();

//        $this->merchantId = Session::get('merchant')['id'];

        View::assign(array(
            'module' => $module,
            'title' => $this->title,
            'con' => $this->con,
            'pageSize' => $this->pageSize
        ));
    }

    public function index()
    {
//        var_dump($this->M->toArray());die;
        if(request()->isPost()){
            $params = request()->param();
            $map = [];

            if(!empty($params['id'])){
                $map[] = ['id', '=', $params['id']];
            }

            if(!empty($params['phone'])){
                $map[] = ['phone', 'like', '%' . $params['phone'] . '%'];
            }

//            $this->model = $this->model->where('merchant_id', $this->merchantId);
//            if(isset($params['title'])){//return 1;
//                // $title = input('title');
//                $this->model = $this->model->where("title", "like", $params['title']);
//            }
//            if(isset($params['author_id'])){
//                // $authorId = input('author_id');var_dump(1);die;
//                $this->model = $this->model->where("author", "like", $params['author_id']);
//            }

//             if(input('tag_id')){
//                 $authorId = input('tag_id');
// //                $map['_string'] = 'FIND_IN_SET(' . $authorId . ', tag_list)';
//                 $map[] = ['exp', Db::raw("FIND_IN_SET(" . $authorId . ", tag_list)")];
//             }

            $total = $this->model
                ->where($map)
                ->count();



            $pageIndex = max(input('page'), 1);
            $pageSize = $this->pageSize;
            $p = ($pageIndex - 1) * $pageSize;

//            $totalMoney = round($this->model
//                ->where($map)
//                ->sum('money'), 2);
//            $totalGoumaiMoney = round($this->model
//                ->where($map)
//                ->sum('goumai_money'), 2);
//            $totalGold = round($this->model
//                ->where($map)
//                ->sum('gold'), 2);
//            $totalGoodsMoney = round($this->model
//                ->where($map)
//                ->sum('goods_money'), 2);
//            $totalVoucher = round($this->model
//                ->where($map)
//                ->sum('voucher'), 2);
            //dd($totalVoucher);
            $list = $this->model
                ->with(['userLevel', 'userVirtualLevel'])
                ->where($map)
                // ->where('rec',1)

//                ->order('balance DESC')
                ->append(['score_format', 'spending_format', 'performance_format'])
                ->limit($p, $pageSize)
                ->select();
// var_dump($list);die;
//            $arr['totalRow']['money'] = $totalMoney;
//            $arr['totalRow']['goumai_money'] = $totalGoumaiMoney;
//            $arr['totalRow']['gold'] = $totalGold;
//            $arr['totalRow']['goods_money'] = $totalGoodsMoney;
//            $arr['totalRow']['voucher'] = $totalVoucher;

            $arr['data'] = $list;
            $arr['code'] = 0;
            // var_dump(1);die;
            $arr['count'] = $total;
            $arr['limit'] = $pageSize;
            $arr['msg'] = "获取" . $this->title . "列表成功";
            return json($arr);
        }else{
//            dd($this->merchantId);
            return View::fetch();
        }
    }

    public function team()
    {
        $userId = input('user_id');
        View::assign(array(
            'user_id'        =>    $userId,
        ));
        return View::fetch();
    }
    public function team2()
    {
//        var_dump($this->M->toArray());die;
        if(request()->isPost()){
            $params = request()->param();
            $userId = $params['user_id'];
            $map = [];
            $map['pid'] = $userId;

//            if(!empty($params['id'])){
//                $map[] = ['id', '=', $params['id']];
//            }
//
//            if(!empty($params['phone'])){
//                $map[] = ['phone', '=', $params['phone']];
//            }

//            $this->model = $this->model->where('merchant_id', $this->merchantId);
//            if(isset($params['title'])){//return 1;
//                // $title = input('title');
//                $this->model = $this->model->where("title", "like", $params['title']);
//            }
//            if(isset($params['author_id'])){
//                // $authorId = input('author_id');var_dump(1);die;
//                $this->model = $this->model->where("author", "like", $params['author_id']);
//            }

//             if(input('tag_id')){
//                 $authorId = input('tag_id');
// //                $map['_string'] = 'FIND_IN_SET(' . $authorId . ', tag_list)';
//                 $map[] = ['exp', Db::raw("FIND_IN_SET(" . $authorId . ", tag_list)")];
//             }

            $total = \app\admin\model\User::where($map)
                ->count();

            $pageIndex = max(input('page'), 1);
            $pageSize = $this->pageSize;
            $p = ($pageIndex - 1) * $pageSize;

            $list = $this->model
                ->where($map)
                // ->where('rec',1)

                ->order('performance DESC')
                ->append(['month_performance', 'last_month_performance', 'last_performance', 'last_month_mine_performance'])
                ->limit($p, $pageSize)
                ->select();
// var_dump($list);die;
            $arr['data'] = $list;
            $arr['code'] = 0;
            // var_dump(1);die;
            $arr['count'] = $total;
            $arr['limit'] = $pageSize;
            $arr['msg'] = "获取" . $this->title . "列表成功";
            return json($arr);
        }else{
            $userId = input('user_id');
            View::assign(array(
                'user_id'        =>    $userId,
            ));
            return View::fetch();
        }
    }

    public function recharge(){
        if(request()->isPost()){
            $params = request()->param();
//            dd($params);
            $userId = $params['id'];
            $amount = bcmul_amount($params['amount']);
            $alias = $params['alias'];
//            $source = $params['source'];

            $msg = '充值';
//            $num = (int)$params['amount'];
            if(isset($params['mode']))
            {
                //增加
                $walletType = 'admin_recharge';
                $des = '【' . ($this->admin)['username'] . '】充值';
                //induce($userId, $amount, $alias = 'money', $type = '', $des = '')
                $save = \app\api\model\User::induce($userId, $amount, $alias, $walletType, $des);
            }else{
                //扣除
                $walletType = 'admin_deduct';
                $msg = '扣除';
                $des = '【' . ($this->admin)['username'] . '】扣除';
                //deduce($user_id, $amount, $alias = 'money', $type = 'benefit_pay', $des = '')
                $save = \app\api\model\User::deduce($userId, $amount, $alias, $walletType, $des);
            }
            if ($save) {
                $arr['status'] = 1;
                $arr['msg'] = $msg . '成功';
            } else {
                $arr['status'] = 0;
                $arr['msg'] = $msg . '失败';
            }
            return $arr;
        }else{
            $id = input('id');
            $info = $this->model->where('id', $id)->find();
            View::assign(array(
                'info'        =>    $info,
            ));
            return View::fetch();
        }
    }

    public function deduct(){
        if(request()->isPost()){
            $params = request()->param();
            $userId = $params['id'];
            $price = $params['amount'];
            $walletType = 17;
            $walletTypeDes = 17;
            $des = '管理员【' . ($this->admin)['username'] . '】扣除';
            $alias = $params['alias'];
            //deduce($userId, $amount, $wallet_type = 0, $wallet_des = 0, $alias = 'money', $des = '')
            $save = \app\api\model\User::deduce($userId, $price, $walletType, $walletTypeDes, $alias, $des);
            if ($save) {
                $arr['status'] = 1;
                $arr['msg'] = '扣除成功';
            } else {
                $arr['status'] = 0;
                $arr['msg'] = '扣除失败';
            }
            return $arr;
        }else{
            $id = input('id');
            $info = $this->model->where('id', $id)->find();
            View::assign(array(
                'info'        =>    $info,
            ));
            return View::fetch();
        }
    }

    public function add(){
        if(request()->isPost()){
            $code = input('code');
            $codeArr = explode(',', $code);
            $sum = $codeArr[0] + $codeArr[1] + $codeArr[2] + $codeArr[3];
            $num = input('num');
            $add = [
                'time'         =>  input('time'),
                'num'     =>  $num,
                'code'     =>  $code,
                'sum'     =>  $sum,
                'status'     =>  1,
            ];

//            var_dump($add);die;

            $this->M->data($add);
            $result = $this->M->save();
            if ($result !== false) {
                (new \app\model\Num())->insert([
                    'name'=>(int)$num + 1,
                    'type'=>1,
                ]);
                $arr['status'] = 1;
                $arr['msg'] = '添加成功';
            } else {
                $arr['status'] = 0;
                $arr['msg'] = '添加失败';
            }
            return $arr;
        }else{
//            $numArr = Db::name('num')
//                ->where('type', 1)
//                ->order('id DESC')->select();
//            View::assign(array(
//                'numArr'        =>    $numArr,
//            ));
            return View::fetch();
        }
    }

    public function edit(){
        if(request()->isPost()){
            $params = request()->param();
//            dd($params);

            $validate = new \app\admin\validate\User();
            $result = $validate->scene('edit')->check($params);
            if(!$result){
                $arr['status'] = 0;
                $arr['msg'] = $validate->getError();
                return json($arr);
            }else{
                if(isset($params['transfer_switch'])) {
                    $params['transfer_switch'] = 'on';
                }else{
                    $params['transfer_switch'] = 'off';
                }
                if(isset($params['withdraw_switch'])) {
                    $params['withdraw_switch'] = 'on';
                }else{
                    $params['withdraw_switch'] = 'off';
                }
                if(isset($params['release_switch'])) {
                    $params['release_switch'] = 'on';
                }else{
                    $params['release_switch'] = 'off';
                }

                if(!empty($params['password2'])){
                    $params['password'] = password_hash($params['password2'], PASSWORD_BCRYPT);
                }else{
                    unset($params['password2']);
                }
                if(!empty($params['pay_password2'])){
                    $params['pay_password'] = md5($params['pay_password2']);
                }else{
                    unset($params['pay_password2']);
                }
                if(empty($params['limit_withdraw'])){
                    $params['limit_withdraw'] = 0;
                }
                if(!empty($params['nickname'])){
                    $params['nickname'] = $params['nickname'];
                }

                if($params['virtual_level_id'] < $params['level_id']){
                    $arr['status'] = 0;
                    $arr['msg'] = '虚拟等级大于或等于真实等级';
                    return json($arr);
                }else{
                    $params['virtual_level_id'] = $params['virtual_level_id'];
                }

                $save = $this->model->update($params);
                if ($save) {
                    $arr['status'] = 1;
                    $arr['msg'] = '修改成功';
                } else {
                    $arr['status'] = 0;
                    $arr['msg'] = '修改失败';
                }
                return json($arr);
            }
        }else{
            $id = input('id');
            $info = $this->model->find($id);
            $level_lists = Level::select();
            View::assign(array(
                'info'        =>    $info,
                'level_lists'=>$level_lists
            ));
            return View::fetch();
        }
    }

    public function del()
    {
        $params = request()->param();
        $uid = $params['id'];
        $phone = $this->model->where('id', $uid)->value('phone');
        $params['phone'] = 'zx' . $phone;
//dd($params);
        $validate = new \app\admin\validate\User();
        $result = $validate->scene('del')->check($params);
        if(!$result){
            $arr['status'] = 0;
            $arr['msg'] = $validate->getError();
            return json($arr);
        }else{
            $update = [
                'id'=>$params['id'],
                'phone'=>$params['phone'],
                'password'=>'123456',
//                'limit_switch'=>'on',
//                'charge_switch'=>'off',
                'status'=>'off',
            ];
            $res = $this->model->update($update);
            if ($res) {
                $arr['status'] = 1;
                $arr['msg'] = '软删除成功';
            } else {
                $arr['status'] = 0;
                $arr['msg'] = '软删除失败';
            }
            return json($arr);
        }
    }

    public function merchant_order()
    {
//        var_dump($this->M->toArray());die;
        if(request()->isPost()){
            $params = request()->param();
            $map = [];

            $orderList = MerchantOrder::where('merchant_id', $this->merchantId)
                ->where('status', 'payed');
//            if(isset($params['title'])){//return 1;
//                // $title = input('title');
//                $this->model = $this->model->where("title", "like", $params['title']);
//            }
//            if(isset($params['author_id'])){
//                // $authorId = input('author_id');var_dump(1);die;
//                $this->model = $this->model->where("author", "like", $params['author_id']);
//            }

//             if(input('tag_id')){
//                 $authorId = input('tag_id');
// //                $map['_string'] = 'FIND_IN_SET(' . $authorId . ', tag_list)';
//                 $map[] = ['exp', Db::raw("FIND_IN_SET(" . $authorId . ", tag_list)")];
//             }

            $list = $orderList
                // ->where($map)
                ->select();

            $total = count($list);

            $pageIndex = max(input('page'), 1);
            $pageSize = $this->pageSize;
            $p = ($pageIndex - 1) * $pageSize;

            $list = $orderList
                // ->where($map)
                // ->where('rec',1)

                ->order('id DESC')
                ->append(['type_format'])
                ->limit($p, $pageSize)
                ->select();
// var_dump($list);die;
            $arr['data'] = $list;
            $arr['code'] = 0;
            // var_dump(1);die;
            $arr['count'] = $total;
            $arr['limit'] = $pageSize;
            $arr['msg'] = "获取" . $this->title . "列表成功";
            return json($arr);
        }else{
            return View::fetch();
        }
    }

    public function order()
    {
//        var_dump($this->M->toArray());die;
        if(request()->isPost()){
            $params = request()->param();
            $map = [];

            $orderList = Order::where('merchant_id', $this->merchantId)
                ->where('status', 'payed');
//            if(isset($params['title'])){//return 1;
//                // $title = input('title');
//                $this->model = $this->model->where("title", "like", $params['title']);
//            }
//            if(isset($params['author_id'])){
//                // $authorId = input('author_id');var_dump(1);die;
//                $this->model = $this->model->where("author", "like", $params['author_id']);
//            }

//             if(input('tag_id')){
//                 $authorId = input('tag_id');
// //                $map['_string'] = 'FIND_IN_SET(' . $authorId . ', tag_list)';
//                 $map[] = ['exp', Db::raw("FIND_IN_SET(" . $authorId . ", tag_list)")];
//             }

            $list = $orderList
                // ->where($map)
                ->select();

            $total = count($list);

            $pageIndex = max(input('page'), 1);
            $pageSize = $this->pageSize;
            $p = ($pageIndex - 1) * $pageSize;

            $list = $orderList
                // ->where($map)
                // ->where('rec',1)

                ->order('id DESC')
                ->append(['type_format'])
                ->limit($p, $pageSize)
                ->select();
// var_dump($list);die;
            $arr['data'] = $list;
            $arr['code'] = 0;
            // var_dump(1);die;
            $arr['count'] = $total;
            $arr['limit'] = $pageSize;
            $arr['msg'] = "获取" . $this->title . "列表成功";
            return json($arr);
        }else{
            return View::fetch();
        }
    }

    //所有用户开户
    public function allUserOpen()
    {
//        $userBank = \app\admin\model\UserBank::where('user_id', 64)->find();

        $userBankList = \app\admin\model\UserBank::where('status', 'pass')->select();

        foreach ($userBankList as $userBank){
            $res = (new \app\admin\model\Setplus())->userOpen($userBank);
            if($res['respCode'] == '00'){
                if($res['status'] == 3){
                    \app\admin\model\UserBank::where('id', $userBank['id'])->update([
                        'status'=>'enabled'
                    ]);
                }
            }else{
                if($res['respCode'] == '94'){
                    \app\admin\model\UserBank::where('id', $userBank['id'])->update([
                        'status'=>'enabled'
                    ]);
                }else{
                    \app\admin\model\UserBank::where('id', $userBank['id'])->update([
                        'msg'=>$res['message']
                    ]);
                }
            }
        }
    }

    public function getTree(){
        $userId = input('user_id');
        $res = $this->model->getUserTree($userId);
        return json($res);
//        dd($res);
    }

    //更改是否限制释放
    public function changeLimitBenefit()
    {
        $id = request()->param('id');
        $status = request()->param('status');
        $value = $status == 'true' ? 'on' : 'off';
        $lists = $this->model->getUserTreeField($id, 'id');
//        dd($lists);
//        dd(implode(',', $lists->toArray()));
//        $save = $this->model->where('id', $id)->update([
//            'limit_benefit'=>$value
//        ]);
        $str = '';
        $num = 1;
        foreach ($lists as $item){
//            $save = $this->model->where('id', $item['id'])->update([
//                'limit_benefit'=>$value
//            ]);
            $str .= $item['id'] . ',';
            $num++;
        }
        $str .= $id;
//        dd($num);
        $save = $this->model->whereIn('id', $str)->update([
            'limit_benefit'=>$value
        ]);
//        dd($str);
        if ($save) {
            $arr['status'] = 1;
            $arr['msg'] = '成功';
        } else {
            $arr['status'] = 0;
            $arr['msg'] = '失败';
        }
        return $arr;
    }

    public function test()
    {
//        $user = \app\admin\model\User::find(87);
//        $amount = 1037;
//        $gold = $user['gold'] + $amount;
//        $score = $user['score'] - $amount;
//        \app\admin\model\User::where('id', 87)->update([
//            'gold'=>$gold,
//            'score'=>$score
//        ]);

        $url = 'http://api.setplus.cn/doc/html/doc/settle/appendix/bank2.html?chapter=4_3';

// 初始化 cURL
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// 抓取网页内容
        $html = curl_exec($ch);

// 关闭 cURL
        curl_close($ch);

// 定义正则表达式，匹配联行号和银行名称
        $pattern = '/<tr>.*?<td>(\d+)<\/td>.*?<td>(.+?)<\/td>.*?<\/tr>/is';

// 在网页内容中匹配正则表达式，获取所有的匹配项
        preg_match_all($pattern, $html, $matches, PREG_SET_ORDER);

// 将匹配项转换为数组
        $results = array();
        foreach ($matches as $match) {
            Bank::create([
                'name'=>$match[2],
                'no'=>$match[1]
            ]);
//            $results[] = array(
//                'bank_code' => $match[1],
//                'bank_name' => $match[2],
//            );
        }

// 输出结果
//        var_dump($results);
    }

    //等级列表
    public function level_lists()
    {
//        var_dump($this->M->toArray());die;
        if(request()->isPost()){
            $params = request()->param();
            $map = [];

            if(!empty($params['benefit_level_id'])){
                $map[] = ['benefit_level_id', '=', $params['benefit_level_id']];
            }

            if(!empty($params['phone'])){
                $map[] = ['phone', 'like', '%' . $params['phone'] . '%'];
            }

//            $this->model = $this->model->where('merchant_id', $this->merchantId);
//            if(isset($params['title'])){//return 1;
//                // $title = input('title');
//                $this->model = $this->model->where("title", "like", $params['title']);
//            }
//            if(isset($params['author_id'])){
//                // $authorId = input('author_id');var_dump(1);die;
//                $this->model = $this->model->where("author", "like", $params['author_id']);
//            }

//             if(input('tag_id')){
//                 $authorId = input('tag_id');
// //                $map['_string'] = 'FIND_IN_SET(' . $authorId . ', tag_list)';
//                 $map[] = ['exp', Db::raw("FIND_IN_SET(" . $authorId . ", tag_list)")];
//             }

            $total = \app\admin\model\User::where($map)
                ->count();


            $pageIndex = max(input('page'), 1);
            $pageSize = $this->pageSize;
            $p = ($pageIndex - 1) * $pageSize;

            $totalMoney = round($this->model
                ->where($map)
                ->sum('money'), 2);
            $totalGoumaiMoney = round($this->model
                ->where($map)
                ->sum('goumai_money'), 2);
            $totalGold = round($this->model
                ->where($map)
                ->sum('gold'), 2);
            $totalGoodsMoney = round($this->model
                ->where($map)
                ->sum('goods_money'), 2);
            $totalVoucher = round($this->model
                ->where($map)
                ->sum('voucher'), 2);
            //dd($totalVoucher);
            $list = $this->model
                ->where($map)
                // ->where('rec',1)
                ->append(['benefit_level_format'])
                ->order('id DESC')
                ->limit($p, $pageSize)
                ->select();
// var_dump($list);die;
            $arr['totalRow']['money'] = $totalMoney;
            $arr['totalRow']['goumai_money'] = $totalGoumaiMoney;
            $arr['totalRow']['gold'] = $totalGold;
            $arr['totalRow']['goods_money'] = $totalGoodsMoney;
            $arr['totalRow']['voucher'] = $totalVoucher;

            $arr['data'] = $list;
            $arr['code'] = 0;
            // var_dump(1);die;
            $arr['count'] = $total;
            $arr['limit'] = $pageSize;
            $arr['msg'] = "获取" . $this->title . "列表成功";
            return json($arr);
        }else{
            $benefitLevelLists = BenefitLevel::select();
            View::assign(array(
                'benefit_level_lists'        =>    $benefitLevelLists,
            ));
            return View::fetch();
        }
    }
}